package com.geekaca.jsp;

import com.geekaca.jsp.service.UserService;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(urlPatterns = "/login")
public class LoginServlet extends HttpServlet {

    private UserService userService = new UserService();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("hello login...");
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setHeader("Content-type", "text/html; charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write("<h1>欢迎登录</h1>");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        HttpSession session = req.getSession();

        int i = userService.checkLogin(username, password);

        if (i > 0) {
            String rememberMe = req.getParameter("rememberMe");

            System.out.println("username " + username);


            session.setAttribute("uname", username);
            session.setAttribute("err", "");
            // 记住我
            if (rememberMe != null && "on".equals(rememberMe)) {
                // 说明勾选了记住我
                // 把用户名和密码存入cookie
                Cookie cookie = new Cookie("uname", username);
                Cookie cookie2 = new Cookie("pass", password);
                resp.addCookie(cookie);
                resp.addCookie(cookie2);
            }
            req.getRequestDispatcher("/brands").forward(req, resp);
        } else {
            session.setAttribute("err", "<h2><font color='red'>登录失败,请重新登录</font></h2>");
            session.setAttribute("uname",null);
            resp.sendRedirect(req.getContextPath() + "/login.jsp");
        }


/*
       if (username.equals(password)) {
            session.setAttribute("err", "");
            session.setAttribute("logged","1");
            // 记住我
            if(rememberMe!=null && "on".equals(rememberMe)){
                // 说明勾选了记住我
                // todo: 把用户名和密码存入cookie
                Cookie cookie = new Cookie("uname",username);
                Cookie cookie2 = new Cookie("pass",password);
                resp.addCookie(cookie);
                resp.addCookie(cookie2);
            }

            req.getRequestDispatcher("/brands").forward(req, resp);
        } else {
            session.setAttribute("err", "<h2>登录失败,请重新登录</h2>");
            session.setAttribute("logged","0");
            resp.sendRedirect(req.getContextPath() + "/login.jsp");
        }*/


    }
}
